package riteh.proba.server.resources;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;

public class Database {
	//TODO: NE RADI ZATVARANJE KONEKCIJE - razlog: ne mogu iterirati kroz ResultSet ako je konekcija otvorena
	//http://stackoverflow.com/questions/7666978/java-sql-sqlexception-operation-not-allowed-after-resultset-closed
	Connection con;
	PreparedStatement statement;
	ResultSet result;
	
	public Database() throws Exception
	{
		Class.forName("com.mysql.jdbc.Driver");

		con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
	}
	
	public void Query(String q, boolean returnId)
	{
		try {
			if (!returnId) statement = con.prepareStatement(q);
			else statement = con.prepareStatement(q, Statement.RETURN_GENERATED_KEYS);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public ResultSet Execute()
	{
		try {
			result = statement.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	//Smije se pozvat SAMO JEDNOM jer modificira next varijablu
	public String GetResultAsString(int resultPosition)
	{
		String r = "";
		try {
			result.next();
			r = result.getString(resultPosition);
		} catch (Exception e) {}
		
		return r;
	}
	
	public int GetResultAsInt(int resultPosition)
	{
		int r = 0;
		try {
			result.next();
			r = result.getInt(resultPosition);
		} catch (Exception e) {}
		
		return r;
	}
	
	public int ExecuteReturnLastId()
	{
		int result = 0;
		
		try {
			statement.executeUpdate();
			ResultSet r = statement.getGeneratedKeys();
			r.next();
			result = r.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public void ExecuteUpdate()
	{		
		try {
			statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void Close()
	{
		try {
			con.close();
		} catch (SQLException e) {}
	}
}
